// pages/shops/apply/index.js
import { getQiniuToken, apiUrls, makeRequest } from '../../utils/api';
import { uploadQiniu } from '../../utils/upload';

const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    categoryItems: [],
    categoryIndex: 0,
    category_id: 3,
    name: '',
    lng: '',
    lat: '',
    address: '',
    tel: '',
    business_licences_number: '',
    business_licences_image: '',
    business_licences_image_local: '',
    introductionCount: 0,
    qiniu_token: '',
    isAgree: true
  },
  /**
   * 分类选择绑定
   */
  bindCategoryPickerChange: function (e) {
    console.log(e);
    const that = this;
    const index = e.detail.value;
    const vId = this.data.categoryItems[index].id;
    that.setData({
      categoryIndex: index,
      category_id: vId
    });
  },

  openChooseLocationMap: function () {
    const that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          address: res.address + '(' + res.name + ')',
          lng: res.longitude,
          lat: res.latitude
        });
      },
    })
  },
  toggleAgree(e) {
    const status = !this.data.isAgree;
    this.setData({
      isAgree: status
    });
  },
  bindSubmit(e) {
    //提交错误描述
    if (!this.wxValidate.checkForm(e)) {
      const error = this.wxValidate.errorList[0]
      // `${error.param} : ${error.msg} `
      wx.showToast({
        title: `${error.msg}`,
        image: '/images/error.png',
        duration: 500
      })
      return false
    }
    else {
      makeRequest({
        url: apiUrls.postApplyItem,
        method: 'POST',
        data: e.detail.value,
        success: function (res) {
          console.log(res);
          if (res.statusCode === 422) {
            wx.showToast({
              title: `${res.data.data[Object.keys(res.data.data)[0]][0]} `,
              image: '/images/error.png',
              duration: 500
            })
          } else if (res.statusCode === 200) {
            wx.showToast({
              title: '提交成功',
              duration: 2000,
              success: function () {
                wx.redirectTo({
                  url: '../mystore/index'
                })
              }
            })
          }
        }
      });
    }
    //console.log(e.detail.value)
  },

  chooseLicenceImage() {
    const that = this
    wx.chooseImage({
      success: function (res) {
        console.log(res);
        const file = res.tempFilePaths[0];
        uploadQiniu(file, that.data.qiniu_token, function (res) {
          const key = JSON.parse(res.data).key;
          that.setData({
            business_licences_image_local: file,
            business_licences_image: key
          });
        });
      },
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.form.photos // 需要预览的图片http链接列表
    })
  },
  previewSingleImage(e) {
    wx.previewImage({
      current: 0, // 当前显示图片的http链接
      urls: [e.currentTarget.id] // 需要预览的图片http链接列表
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this;
    this.wxValidate = App.wxValidate(
      {
        name: {
          required: true,
          minlength: 2,
          maxlength: 10,
        },
        tel: {
          required: true,
          tel: true,
        },
        address: {
          required: true,
          minlength: 2,
          maxlength: 100,
        },
        lng: {
          required: true,
        },
        lat: {
          required: true,
        },
        business_licences_number: {
          required: true,
        },
        business_licences_image: {
          required: true,
        }
      }
      , {
        name: {
          required: '请填写商铺名称',
          minlength: '商铺名称至少两个字哦'
        },
        tel: {
          required: '请填写电话号码',
        },
        address: {
          required: '请选择地址',
        },
        lng: {
          required: '位置必须选择'
        },
        lat: {
          required: '位置必须选择'
        },
        business_licences_number: {
          required: '营业执照必须填写',
        },
        business_licences_image: {
          required: '营业执照必须上传',
        }
      }
    )
    makeRequest({
      url: apiUrls.getCategories,
      method: 'GET',
      success: function (res) {
        self.setData({ categoryItems: res.data.data });
      }
    })

    makeRequest({
      url: apiUrls.getQiniuToken,
      method: 'GET',
      success: function (res) {
        self.setData({ qiniu_token: res.data.uptoken });
      }
    })
  }
})